package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.MaoYanMovieCityCinemaBoxModel;
import com.xiaotu.common.redis.RedisClientTemplate;
import com.xiaotu.common.util.CacheHandler;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DateUtils;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.PropertiesUtil;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.UUIDUtils;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import com.xiaotu.spider.APageProcessor;
import com.xiaotu.spider.AUrlPageProcessor;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Html;

/***
 * 城市票房
 * 影投票房
 */
@Component("MaoYanMovieCityBoxPageProcessor")
public class MaoYanMovieCityBoxPageProcessor extends APageProcessor {

	
	private Map<String,String> cookies = new HashMap<String,String>();
	
	{
		cookies.put("Cookie", PropertiesUtil.getProperty("BoxOffice.site.Cookie"));
	}
	
	private String CITY_URL = "http://piaofang.maoyan.com/movie/%s/cityBox?date=%s";//分城票房
	
	private String CITY_BOX_URL = "http://piaofang.maoyan.com/movie/%s/box-ajax?movieId=%s&boxLevel=4&date=%s&offset=0&type=areaBox&method=change";
	

	@Autowired
    protected CacheHandler cacheHandler;
	
	@Override
	public void process(Page page) {
		
		Map<String, Object> extrasMap = page.getRequest().getExtras();
		
		switch (this.getPageDataType(page))
        {
            case "cityBox":
                this.checkCityProcess(page,extrasMap);
                break;
            case Constants.PageDataType.TV_CITY:
                this.cityBoxProcess(page,extrasMap);
                break;
        }
	}
	
	/** cityBoxProcess(分成数据爬取)   
	 * 创建人：张晓   
	 * 创建时间：2020年3月18日 下午2:24:25    
	 * 修改备注： 
	 * @param page
	 * @param extrasMap  
	 */
	private void cityBoxProcess(Page page, Map<String, Object> extrasMap) {
		String rawText = page.getRawText();
		if(null == rawText || StringUtils.isBlank(rawText)){
			throw new SpiderException(SpiderExceptionCode.DataInvalideException);
		}
		JSONObject json = GsonUtils.fromJson(rawText,JSONObject.class);
		JSONArray jsonArray = json.getJSONObject("data").getJSONArray("detailList");
		if(jsonArray.size()==0 || jsonArray.isEmpty())
			throw new SpiderException(SpiderExceptionCode.DataInvalideException);
		List<MaoYanMovieCityCinemaBoxModel> cityList = new ArrayList<MaoYanMovieCityCinemaBoxModel>();
		for(int i = 0;i<jsonArray.size();i++){
			JSONObject obj = (JSONObject) jsonArray.get(i);
			MaoYanMovieCityCinemaBoxModel maoYanMovieCityCinemaModel = new MaoYanMovieCityCinemaBoxModel(
					extrasMap.get("playdate").toString(),
            		UUIDUtils.getId(),
            		extrasMap.get("dataid").toString(),
            		extrasMap.get("mvname").toString(),
            		obj.getString("name"),
            		obj.getString("boxInfo").replaceAll("[--]", "").equals("")?"":obj.getString("boxInfo"),
            		obj.getString("boxRate").replace("--", ""), 
            		obj.getString("showRate").replace("--", ""), 
            		obj.getString("avgShowView").replace("--", ""),
            		obj.getString("sumBoxInfo").replace("--", ""),
            		obj.getString("seatRate").replace("--", ""),
            		obj.getString("primeShowRate").replace("--", ""),
            		obj.getString("viewInfo").replace("--", ""),
                    obj.getString("showInfo").replace("--", ""));
            		cityList.add(maoYanMovieCityCinemaModel);
		}
		page.putField(MaoYanMovieCityCinemaBoxModel.class.getName(), cityList);
	}

	/**
     * 检查分城数据
     * @param page
     */
    private void checkCityProcess(Page page,Map<String, Object> extrasMap)
    {
    	
    	String filed = extrasMap.get("dataid").toString()+"_"+extrasMap.get("playdate");
    	
    	//将缓存数据删除
    	cacheHandler.hDel("MAOYAN_SHADOW_BOX", filed);
    	cacheHandler.hSet("MAOYAN_SHADOW_BOX_SUCCESS", filed, extrasMap);
		//当前页面的日期
    	String currPageDate = page.getHtml().xpath("//span[@class='date']//text()").get();
    	//当前请求日期
    	String currParamDate = DateUtils.matchDate(RegexUtils.REGEX_DATE,page.getRequest().getUrl());
    	
    	if(null == currPageDate || currPageDate.equals("unde-fi-ned")){
    		throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    	}
    	currPageDate = DateUtils.formatDate(DateUtils.CH_DAY_FORMAT,DateUtils.DAY_FORMAT,currPageDate);
    	if(currPageDate == null){
    		throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    	}
    	if(RegexUtils.regexMatch(RegexUtils.REGEX_DATE, currPageDate) && 
    			RegexUtils.regexMatch(RegexUtils.REGEX_DATE, currParamDate)){
    		if(!currPageDate.equals(currParamDate)){
    			throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    		}
    	}else{
    		throw new SpiderException(SpiderExceptionCode.DataInvalideException);
    	}
    	
        PageUtils.addTargetRequest(page, String.format(CITY_BOX_URL, extrasMap.get("dataid"),extrasMap.get("dataid"),extrasMap.get("playdate")), extrasMap);
    }
	
	@Override
	protected Request getStartRequest(JSONObject target){
		Request req = new Request(String.format(CITY_URL, target.getInt("dataid"), target.getString("playdate")));
		req.putExtra("dataid", target.getInt("dataid"));
		req.putExtra("mvname", target.getString("mvname"));
		req.putExtra("playdate", target.getString("playdate"));
		return req;
	};

	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("/cityBox"))
            return "cityBox";
        else if(url.contains("boxLevel=4")){
        	return Constants.PageDataType.TV_CITY;
        }
        return null;
	}
	
}
